<template>
  <div class="storage-view">
    <div class="page-header">
      <div class="header-content">
        <el-button icon="el-icon-arrow-left" @click="goBack">返回首页</el-button>
        <h2>入库管理</h2>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧商品查询区域 -->
      <div class="product-list-container">
        <div class="search-panel">
          <div class="search-row-container">
            <el-input
              placeholder="搜索商品名称"
              v-model="searchText"
              class="search-input"
              clearable
              @keyup.enter.native="searchProducts"
            >
              <el-button slot="append" icon="el-icon-search" @click="searchProducts"></el-button>
            </el-input>
            
            <el-select 
              v-model="selectedCategory" 
              placeholder="商品分类" 
              clearable 
              @change="searchProducts"
              @focus="loadCategories"
              class="select-input">
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            
            <el-select 
              v-model="sortOption" 
              placeholder="排序方式" 
              @change="searchProducts"
              class="select-input">
              <el-option label="价格从低到高" value="priceAsc"></el-option>
              <el-option label="价格从高到低" value="priceDesc"></el-option>
              <el-option label="库存从低到高" value="stockAsc"></el-option>
              <el-option label="库存从高到低" value="stockDesc"></el-option>
            </el-select>
          </div>
        </div>

        <div class="table-container">
          <el-table
            :data="displayProductList"
            border
            style="width: 100%"
            v-loading="loading"
            :resizable="false"
            height="100%"
          >
            <el-table-column prop="code" label="商品编号" width="200" align="center" :resizable="false"></el-table-column>
            <el-table-column prop="name" label="商品名称" width="180" align="center" :resizable="false"></el-table-column>
            <el-table-column prop="category" label="分类" width="170" align="center" :resizable="false"></el-table-column>
            <el-table-column prop="price" label="价格" width="160" align="center" :resizable="false">
              <template slot-scope="scope">
                ¥{{ scope.row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="140" align="center" :resizable="false"></el-table-column>
            <el-table-column label="操作" width="90" align="center" fixed="right" :resizable="false">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-plus"
                  circle
                  @click="addToCart(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>

      <!-- 右侧购物车区域 -->
      <div class="cart-container">
        <div class="table-container">
          <el-table
            :data="cartItems"
            border
            style="width: 100%"
            :resizable="false"
            height="100%"
          >
            <el-table-column prop="name" label="商品名称" width="175" align="center" :resizable="false"></el-table-column>
            <el-table-column label="入库数量" width="210" align="center" :resizable="false">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.quantity"
                  :min="1"
                  :max="999"
                  size="mini"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="90" align="center" :resizable="false">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  circle
                  @click="removeFromCart(scope.$index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="cart-footer">
          <el-button type="danger" @click="clearCart" :disabled="!cartItems.length">清空</el-button>
          <el-button type="primary" @click="submitStorage" :disabled="!cartItems.length">确认入库</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'StorageView',
  data() {
    return {
      searchText: '',
      selectedCategory: '',
      sortOption: '',
      loading: false,
      allProducts: [],
      filteredProductList: [],
      cartItems: [],
      currentPage: 1,
      pageSize: 10,
      categoryOptions: [],
      categoriesLoaded: false,
      scanBuffer: '', // 用于存储扫码枪输入的字符
      lastKeyTime: 0,  // 上次按键时间
      maxScanGap: 20,   // 扫码枪按键间隔(毫秒)
      total: 0
    }
  },
  computed: {
    displayProductList() {
      return this.filteredProductList;
    }
  },
  created() {
    // 添加键盘事件监听器，用于捕获扫码枪输入
    window.addEventListener('keydown', this.handleKeyDown);
    // 加载商品数据
    this.loadProducts();
  },
  beforeDestroy() {
    // 移除键盘事件监听器
    window.removeEventListener('keydown', this.handleKeyDown);
  },
  methods: {
    goBack() {
      // 重置所有状态
      this.resetAll();
      // 返回首页
      this.$emit('close');
    },
    
    // 重置所有状态
    resetAll() {
      // 重置搜索条件
      this.searchText = '';
      this.selectedCategory = '';
      this.sortOption = '';
      // 重置分页
      this.currentPage = 1;
      this.pageSize = 10;
      // 清空购物车
      this.cartItems = [];
      // 重置扫码缓存
      this.scanBuffer = '';
      this.lastKeyTime = 0;
    },
    
    loadProducts() {
      // 重置所有状态
      this.resetAll();
      // 调用API获取商品列表初始数据，默认第一页
      this.searchProducts();
    },
    searchProducts() {
      this.loading = true;
      
      // 构建查询参数
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.searchText || ''
      };
      
      // 如果选择了分类，添加categoryId
      if (this.selectedCategory) {
        // 从分类选项中找到对应的分类对象
        const category = this.categoryOptions.find(c => c.value === this.selectedCategory);
        if (category && category.id) {
          params.categoryId = category.id;
        }
      }
      
      // 添加排序参数
      if (this.sortOption) {
        switch (this.sortOption) {
          case 'priceAsc':
            params.orderBy = 'price';
            params.orderDirection = 'asc';
            break;
          case 'priceDesc':
            params.orderBy = 'price';
            params.orderDirection = 'desc';
            break;
          case 'stockAsc':
            params.orderBy = 'stock';
            params.orderDirection = 'asc';
            break;
          case 'stockDesc':
            params.orderBy = 'stock';
            params.orderDirection = 'desc';
            break;
        }
      }
      
      // 调用API获取分页筛选后的商品列表
      this.$http.get('/product/list', { params })
        .then(response => {
          console.log('获取商品列表成功:', response);
          if (response.code === 200 && response.data) {
            // 过滤掉status为"locked"的下架商品
            const records = response.data.records || [];
            this.filteredProductList = records.filter(product => product.status !== 'locked');
            this.total = response.data.total || 0;
            
            // 如果有下架商品被过滤，调整total值
            if (records.length > this.filteredProductList.length) {
              this.total -= (records.length - this.filteredProductList.length);
            }
            
            // 打印库存数据，用于调试
            console.log('库存数据:', this.filteredProductList.map(item => 
              `${item.name}: stock=${item.stock}`).join(', '));
          } else {
            this.filteredProductList = [];
            this.total = 0;
            console.error('API返回错误:', response);
          }
          this.loading = false;
        })
        .catch(error => {
          console.error('获取商品列表失败:', error);
          this.$message.error('获取商品列表失败');
          this.filteredProductList = [];
          this.total = 0;
          this.loading = false;
        });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.searchProducts();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.searchProducts();
    },
    addToCart(product) {
      // 检查商品是否已在购物车中
      const existingItem = this.cartItems.find(item => item.id === product.id);
      
      if (existingItem) {
        // 如果商品已在购物车中，增加数量
        existingItem.quantity++;
      } else {
        // 如果是新商品，添加到购物车
        this.cartItems.push({
          id: product.id,
          name: product.name,
          price: product.price,
          quantity: 1
        });
      }
    },
    removeFromCart(index) {
      // 直接移除商品，不使用变量
      this.cartItems.splice(index, 1)
    },
    clearCart() {
      this.$confirm('确定要清空入库列表吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.cartItems = []
        this.$message({
          type: 'success',
          message: '入库列表已清空'
        })
      }).catch(() => {})
    },
    submitStorage() {
      // 确保购物车中有商品
      if (this.cartItems.length === 0) {
        this.$message.warning('请先添加商品到入库列表');
        return;
      }
      
      // 转换购物车数据为后端需要的格式
      const requestData = this.cartItems.map(item => ({
        id: item.id,
        name: item.name,
        stock: item.quantity,
        number: item.quantity
      }));
      
      console.log('准备提交入库数据:', requestData);
      
      // 显示确认对话框
      this.$confirm(`确定要入库这 ${this.cartItems.length} 种商品吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 调用后端API
        this.$http.post('/inventory/saveBatch', requestData)
          .then(response => {
            console.log('入库操作返回结果:', response);
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '入库操作成功!'
              });
              // 重置所有状态
              this.resetAll();
              // 通知父组件刷新商品列表
              this.$emit('refresh-products');
              // 返回首页
              this.$emit('close');
            } else {
              this.$message.error(response.message || '入库操作失败');
            }
          })
          .catch(error => {
            console.error('入库操作失败:', error);
            this.$message.error('入库操作失败，请稍后重试');
          });
      }).catch(() => {
        // 用户取消操作，不做任何处理
      });
    },
    // 处理扫描到的商品编号
    processScannedCode(code) {
      if (!code) return;
      
      console.log('扫描到商品编号:', code);
      
      // 在当前显示的商品列表中查找匹配的商品
      const matchedProduct = this.displayProductList.find(product => product.code === code);
      
      if (matchedProduct) {
        // 直接添加到购物车（addToCart方法会处理数量累加）
        this.addToCart(matchedProduct);
        
        // 高亮显示匹配的商品行
        this.$nextTick(() => {
          const table = this.$el.querySelector('.product-list-container .el-table__body-wrapper');
          if (table) {
            const rows = table.querySelectorAll('.el-table__row');
            rows.forEach((row, index) => {
              if (this.displayProductList[index].id === matchedProduct.id) {
                row.classList.add('scan-highlight');
                setTimeout(() => {
                  row.classList.remove('scan-highlight');
                }, 2000);
              }
            });
          }
        });
      } else {
        // 如果当前页面没有找到，可能需要从所有产品中搜索
        // 设置搜索文本为扫描到的编号，并触发搜索
        this.searchText = code;
        this.searchProducts();
      }
    },
    // 处理键盘输入，用于捕获扫码枪数据
    handleKeyDown(event) {
      // 如果用户正在输入框中输入或者页面中有激活的输入元素，不处理扫码
      if (event.target.tagName === 'INPUT' || 
          event.target.tagName === 'TEXTAREA' || 
          event.target.isContentEditable ||
          document.activeElement.tagName === 'INPUT' ||
          document.activeElement.tagName === 'TEXTAREA' ||
          event.target.className.includes('el-input') ||
          event.target.closest('.el-input') ||
          event.target.closest('.search-panel') ||
          event.target.closest('.pagination-container')) {
        return;
      }
      
      const currentTime = new Date().getTime();
      
      // 如果按键间隔大于扫码枪最大间隔，则认为是新的扫码开始
      if (currentTime - this.lastKeyTime > this.maxScanGap) {
        this.scanBuffer = '';
      }
      
      // 更新上次按键时间
      this.lastKeyTime = currentTime;
      
      // 如果按下的是回车键，认为扫码结束，处理扫码数据
      if (event.keyCode === 13) {
        this.processScannedCode(this.scanBuffer);
        this.scanBuffer = '';
        event.preventDefault(); // 阻止回车默认行为
        return;
      }
      
      // 将按键字符添加到缓冲区
      if (event.key && event.key.length === 1) {
        this.scanBuffer += event.key;
      }
    },
    // 加载商品分类列表
    loadCategories() {
      // 如果分类已经加载过，则不再重复加载
      if (this.categoriesLoaded) {
        return;
      }
      
      this.$http.get('/category/getAllCategory').then(response => {
        console.log('获取分类列表成功:', response);
        if (response.data && Array.isArray(response.data)) {
          // 将返回的categoryVO列表转换为下拉框选项格式
          this.categoryOptions = response.data.map(category => {
            return {
              id: category.id, // 保存id用于查询
              value: category.name,
              label: category.name
            };
          });
          this.categoriesLoaded = true;
        }
      }).catch((error) => {
        console.error('获取分类列表失败:', error);
        this.$message.error('获取分类列表失败');
      });
    }
  }
}
</script>

<style scoped>
.storage-view {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
  padding: 0;
  margin: 0;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.page-header {
  background-color: #304156;
  padding: 0;
  color: white;
  width: 100%;
  z-index: 10;
  margin: 0;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

.header-content {
  display: flex;
  align-items: center;
  padding: 10px 20px;
}

.page-header h2 {
  margin-left: 20px;
  margin-bottom: 0;
  color: white;
}

.page-header .el-button {
  background-color: transparent;
  border-color: white;
  color: white;
}

.main-content {
  display: flex;
  flex: 1;
  gap: 20px;
  padding: 10px 20px 20px;
  height: calc(100% - 50px);
  overflow: hidden;
  min-height: 600px;
}

.product-list-container {
  flex: 2;
  display: flex;
  flex-direction: column;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
  background-color: #fff;
  overflow: hidden;
  height: 100%;
}

.search-panel {
  margin-bottom: 15px;
}

.search-row-container {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 10px;
  width: 100%;
}

.search-input {
  width: 40%;
  min-width: 180px;
}

.select-input {
  width: 30%;
  min-width: 120px;
}

.table-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  height: calc(100% - 80px);
  min-height: 300px;
}

.el-table {
  width: 100% !important;
  table-layout: fixed;
}

.el-table__body {
  width: 100% !important;
}

/* 禁用表格列宽调整 */
.el-table .el-table__column-resize-proxy {
  display: none !important;
}

.el-table colgroup col {
  width: auto !important;
}

.cart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
  background-color: #fff;
  overflow: hidden;
  height: 100%;
}

.products-header, .cart-header {
  margin-bottom: 10px;
}

.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cart-footer .el-button--primary {
  background-color: #304156;
  border-color: #304156;
}

.el-table__row .el-button--primary {
  background-color: #304156;
  border-color: #304156;  
}

.pagination-container {
  margin-top: 10px;
}

/* 添加扫码成功高亮样式 */
.scan-highlight {
  background-color: rgba(103, 194, 58, 0.2) !important;
  animation: fade-highlight 2s;
}

@keyframes fade-highlight {
  0% { background-color: rgba(103, 194, 58, 0.5); }
  100% { background-color: rgba(103, 194, 58, 0); }
}
</style> 